﻿using Raffles.OA.Data;
using Raffles.OA.Service;
using Raffles.OA.Utility;
using Raffles.OA.WebApp.App_Start;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace Raffles.OA.WebApp.Controllers
{
    public class HomeController : BaseActionController
    {
        private UserService _userService;

        public HomeController()
        {
            _userService = new UserService();
        } 

        /// <summary>
        /// 系统首页
        /// </summary>
        /// <returns></returns>
        public ActionResult Default()
        {
            return View();
        }

        /// <summary>
        /// 后台工具
        /// </summary>
        /// <returns></returns>
        public ActionResult Tool()
        {
            return View();
        }

        /// <summary>
        /// 付款申请数量
        /// </summary>
        /// <returns></returns>
        public async Task<ActionResult> GetPayApplyCount()
        {
            var count = await _dbContext.Queryable<ProjectEntity>()
                                .Where(x => x.FormType == ProjectFormEnum.FinanceSettlement.ToString())//成本结算单
                                .Where(x => x.PayStatus == (int)ProjectCostPayEnum.PayAudit || x.PayStatus == (int)ProjectCostPayEnum.PayAuditPass)//审核中和审核通过
                                .Where(x => SqlFunc.SplitIn(x.PayAuditId, OperatorProvider.Provider.GetCurrent().Id.ToString()))//当前操作人
                                .CountAsync();
            return Content(DataResult<int>.Success(count).ToJson());
        }

        /// <summary>
        /// 首页图表
        /// </summary>
        /// <returns></returns>
        public async Task<ActionResult> ReportChartPage()
        {
            ReportChartVo reportChartVo = new ReportChartVo();
            //后续做统计时需要考虑项目的状态筛选
            ISugarQueryable<ProjectEntity> queryable = _dbContext.Queryable<ProjectEntity>()
                                                                 .Where(x => x.FormType == ProjectFormEnum.CustomerSettlement.ToString() && SqlFunc.ToDate(x.DepartureDate).Year == DateTime.Now.Year);
            ISugarQueryable<ProjectEntity> querySalerMOnthAmountsClone = queryable.Clone();
            ISugarQueryable<ProjectEntity> querySalerYearAmountsClone = queryable.Clone();
            ISugarQueryable<ProjectEntity> queryGroupYearAmountsClone = queryable.Clone();
            ISugarQueryable<ProjectEntity> queryablePersonal = queryable.WhereIF(OperatorProvider.Provider.GetCurrent().DataScope == (int)DataScopeEnum.SELF, x => x.SaleManagerId == OperatorProvider.Provider.GetCurrent().Id);

            reportChartVo.ProjectTotal = await queryablePersonal.CountAsync();
            reportChartVo.SaleAmountTotal = await queryablePersonal.SumAsync(it => it.SaleRMBAmountAfterTax);

            

            #region 销售个人月销售总额

            var salers = await _userService.GetSalerList(null);

            reportChartVo.SalerMonthAmounts.Salers = salers.Select(x => x.RealName).ToList();

            var groupByMonthAmount = querySalerMOnthAmountsClone.GroupBy(x => new
            {
                Month = x.DepartureDate.Value.ToString("yyyy-MM"),
                SaleManagerId = x.SaleManagerId,
                SaleManagerName = x.SaleManagerName
            })
            .Select(x => new
            {
                SaleManagerId = x.SaleManagerId,
                SaleManagerName = x.SaleManagerName,
                Month = x.DepartureDate.Value.ToString("yyyy-MM"),
                Amount = SqlFunc.AggregateSum(x.SaleRMBAmountAfterTax)
            })
            .MergeTable()
            .ToList();

            List<SalerMonthAmountItemDetail> details = new List<SalerMonthAmountItemDetail>();
            foreach (var item in salers)
            { 
                List<decimal> monthDatas = new List<decimal>();
                //如果当前销售员没有销售数据
                if (!groupByMonthAmount.Any(x => x.SaleManagerId == item.Id))
                {
                    monthDatas = new List<decimal>(new decimal[12]);
                }
                else
                {
                    for (int i = 1; i <= 12; i++)
                    {
                        var data = groupByMonthAmount.FirstOrDefault(x => x.SaleManagerId == item.Id && x.Month.ToDate().Month == i);
                        if (data != null)
                        {
                            monthDatas.Add(data.Amount.ToDecimal());
                        }
                        else
                        {
                            monthDatas.Add(0);
                        }
                    }
                }
                details.Add(new SalerMonthAmountItemDetail
                {
                    name = item.RealName,
                    data = monthDatas
                });
            }
            reportChartVo.SalerMonthAmounts.SalerMonthAmountItemDetails = details;

            #endregion 销售个人月销售总额

            #region 销售个人年销售占比

            reportChartVo.SalerYearAmountRates = querySalerYearAmountsClone.GroupBy(x => new
            {
                x.SaleManagerId,
                x.SaleManagerName
            })
            .Select(x => new SalerYearAmountRateItem
            {
                name = x.SaleManagerName,
                value = SqlFunc.AggregateSum(x.SaleRMBAmountAfterTax)
            })
            .MergeTable()
            .ToList();

            #endregion 销售个人年销售占比

            #region 团队年销售总额

            var groupByGroupAmount = queryGroupYearAmountsClone.GroupBy(x => new
            {
                Month = x.DepartureDate.Value.ToString("yyyy-MM")
            })
            .Select(x => new
            {
                Month = x.DepartureDate.Value.ToString("yyyy-MM"),
                Amount = SqlFunc.AggregateSum(x.SaleRMBAmountAfterTax)
            })
            .MergeTable()
            .ToList();

            List<decimal> groupDatas = new List<decimal>();
            for (int i = 1; i <= 12; i++)
            {
                var data = groupByGroupAmount.FirstOrDefault(x => x.Month.ToDate().Month == i);
                if (data != null)
                {
                    groupDatas.Add(data.Amount.ToDecimal());
                }
                else
                {
                    groupDatas.Add(0);
                }
            }
            reportChartVo.GroupYearAmounts = groupDatas;

            #endregion

            return Content(DataResult<ReportChartVo>.Success(reportChartVo).ToJson());
        }
    }
}